package com.jt.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.springframework.util.StringUtils;

public class ObjectMapperUtil {
    //定义常量对象.优势1:对象独一份,节省空间.优势2:对象不允许别人任意篡改
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 1.将任意的对象转化为json
     * 任意对象使用object来接
     * 返回值是Json串,应该是String
     */
    public static String toJson(Object object) {
        try {
            if (object == null) {
                throw new RuntimeException("传入的对象不能为空");
            }
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            //应该将异常检查,转换为运行时异常
            throw new RuntimeException("传递的对象不支持json转化/检查是否含有get/set方法");
        }
    }

    //2.将任意的json串转为对象,传递什么类型就转化为什么类型
    public static <T> T toObject(String json, Class<T> target) {

        try {
            if (StringUtils.isEmpty(json) || target == null) {
                throw new RuntimeException("传递的参数不能为空");
            }
            return objectMapper.readValue(json, target);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("json转化异常");
        }

    }
}
